package com.k.kc.util;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author k
 */
public class HashKit {

    private static final java.security.SecureRandom RANDOM = new java.security.SecureRandom();
    private static final char[] CHAR_ARRAY = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '_', '-'
    };

    protected static MessageDigest getDigest(String algorithmName) throws NoSuchAlgorithmException {
        return MessageDigest.getInstance(algorithmName);
    }

    public static byte[] hash(String algorithm, byte[] data) throws NoSuchAlgorithmException {
        MessageDigest md5 = getDigest(algorithm);
        md5.update(data);
        return md5.digest();
    }

    public static byte[] hashWithSalt(String algorithm, byte[] contentByte, byte[] saltByte) throws NoSuchAlgorithmException {
        MessageDigest digest = getDigest(algorithm);
        if (saltByte != null) {
            digest.reset();
            digest.update(saltByte);
        }
        return digest.digest(contentByte);
    }

    public static String hashToHex(String algorithm, String srcStr) {
        try {
            byte[] bytes = hash(algorithm, srcStr.getBytes(StandardCharsets.UTF_8));
            return toHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("hash error.");
        }
    }

    public static String hashWithSaltToHex(String algorithm, String srcStr, String salt) {
        try {
            byte[] bytes = hashWithSalt(algorithm, srcStr.getBytes(StandardCharsets.UTF_8), salt.getBytes(StandardCharsets.UTF_8));
            return toHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("hash error.");
        }
    }

    public static String md5(String srcStr) {
        return hashToHex("MD5", srcStr);
    }

    public static String md5(String src, String salt) {
        return hashWithSaltToHex("MD5", src, salt);
    }

    public static String sha1(String srcStr) {
        return hashToHex("SHA-1", srcStr);
    }

    public static String sha256(String srcStr) {
        return hashToHex("SHA-256", srcStr);
    }

    public static String sha256(String srcStr, String salt) {
        return hashWithSaltToHex("SHA-256", srcStr, salt);
    }

    public static String sha384(String srcStr) {
        return hashToHex("SHA-384", srcStr);
    }

    public static String sha512(String srcStr) {
        return hashToHex("SHA-512", srcStr);
    }

    public static byte[] hmacSHA(String algorithm, byte[] key, byte[] data) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);
        return mac.doFinal(data);
    }

    public static byte[] HmacSHA256(byte[] data, byte[] key) throws java.lang.Exception {
        return hmacSHA("HmacSHA256", key, data);
    }

    public static byte[] HmacSHA512(byte[] data, byte[] key) throws Exception {
        return hmacSHA("HmacSHA512", key, data);
    }

    public static String toHex(byte[] bytes) {
        return ByteUtils.toHex(bytes);
    }

    public static String byteArrayToBase64(byte[] b) {
        return Base64.getEncoder().encodeToString(b);
    }

    public static byte[] base64ToByteArray(String base64Str, Charset charset) {
        return Base64.getDecoder().decode(base64Str.getBytes(charset));
    }

    /**
     * md5 128bit 16bytes
     * sha1 160bit 20bytes
     * sha256 256bit 32bytes
     * sha384 384bit 48bytes
     * sha512 512bit 64bytes
     */
    public static String generateSalt(int saltLength) {
        StringBuilder salt = new StringBuilder();
        for (int i = 0; i < saltLength; i++) {
            salt.append(CHAR_ARRAY[RANDOM.nextInt(CHAR_ARRAY.length)]);
        }
        return salt.toString();
    }

    public static String generateSaltForSha256() {
        return generateSalt(32);
    }

    public static String generateSaltForSha512() {
        return generateSalt(64);
    }

    public static boolean slowEquals(byte[] a, byte[] b) {
        if (a == null || b == null) {
            return false;
        }
        int diff = a.length ^ b.length;
        for (int i = 0; i < a.length && i < b.length; i++) {
            diff |= a[i] ^ b[i];
        }
        return diff == 0;
    }

    public static void main(String[] args) {
        //e10adc3949ba59abbe56e057f20f883e,Command_123
        String pwd = "Command_123";
        // YzcmCZNvbXocrsz9dm8e
        String salt = "YzcmCZNvbXocrsz9dm8e";

        System.out.println("salt length:" + salt.getBytes().length);
        System.out.println("md5:" + HashKit.md5(pwd));
        System.out.println("md5 salt:" + HashKit.md5(pwd, salt));
        System.out.println("sha256:" + HashKit.sha256(pwd));
        System.out.println("sha256Salt:" + HashKit.sha256(pwd, salt));
        System.out.println("sha256Salt:" + HashKit.sha256(pwd, salt));
        // BASE64
        byte[] byteSrc = "123".getBytes(StandardCharsets.UTF_8);
        String base64Encode = Base64.getEncoder().encodeToString(byteSrc);
        String base64Src = new String(Base64.getDecoder().decode(base64Encode), StandardCharsets.UTF_8);
        System.out.println("base64Encode:" + base64Encode);
        System.out.println("base64Decode:" + base64Src);

    }
}
